package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.StringJoiner;

@Slf4j
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Override
    public void insertAudit(Application application) {
        //遍历审批id集合
        List<Long> auditUserIdList = application.getAuditUserIdList();
        for (int i = 0; i < auditUserIdList.size(); i++) {
            Audit audit = new Audit();
            //申请单id
            audit.setApplicationId(application.getId());
            //审批人id
            audit.setAuditUserId(auditUserIdList.get(i));
            //审批状态 i==0 设置待我审核
            if(i==0){
                //设置为待我审核
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else{
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            //审批顺序，上级是0，上上级是1
            audit.setAuditSort(i);
            //审批单数据入库
            auditMapper.insertAudit(audit);
        }
    }

    @Override
    public List<AuditVO> selectAudits(AuditQuery auditQuery) {
        List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
        for (int i = 0; i < auditVOS.size(); i++) {
            AuditVO auditVO = auditVOS.get(i);
            //准备审批人数据
            auditUserList(auditVO);
        }
        //千万要记得返回！！
        return auditVOS;
    }

    @Override
    public void updateAudit(AuditSaveParam saveParam) {
        //准备一个Audit对象
        Audit audit = new Audit();
        BeanUtils.copyProperties(saveParam,audit);
        //准备application对象，修改审核状态同步修改application状态
        Application application = new Application();
        application.setId(audit.getApplicationId());
        //前端操作是通过的操作，审批单的状态是30，已审核的状态
        //判断当前状态是否为已审核的状态
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){
            //前端是审批通过的操作，需要将audit更新入库，修改数据库中当前审批单对象的状态修改为“已审核”
            auditMapper.update(audit);
            //查询当前申请单是否有其他的审核信息
            //获取申请单的id，使用AuditQuery进行查询
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            //判断count是否为0，是0表示当前申请单没有继续要审核的信息了
            if(count>0){//表示当前申请单还是有未审核的信息
                //修改审批顺序，当前的审核信息数据+1
                auditQuery.setAuditSort(auditQuery.getAuditSort()+1);
                //继续查询下一条要审核的数据
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                //判断auditVOList是否为空，确保auditVOList集合不能为空
                if(auditVOList!=null && auditVOList.size()>0){
                    //取出auditVOList第一条数据，
                    AuditVO auditVO = auditVOList.get(0);
                    //创建一个新的Audit对象，用于更新数据库
                    Audit audit2 = new Audit();
                    //设置审核的id
                    audit2.setId(auditVO.getId());
                    //修改审核状态--待我审核
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit2);
                }
                //设置申请单的状态为审核中
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else{//没有未审核的数据
                //设置申请单的状态为已审核
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else if(audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())){//前端传送的状态为驳回
            auditMapper.update(audit);
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //根据申请单id查询其余的审批信息
            List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
            //如果集合不为空，审批信息一一删除
            if(auditVOS!=null&&auditVOS.size()>0){
                for (int i = 0; i < auditVOS.size(); i++) {
                    AuditVO auditVO = auditVOS.get(i);
                    //审核单状态处于“待我审核”的时候删除，还未审批的
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.MY_PENDING.getCode())){
                        auditMapper.deleteById(audit.getId());
                    }
                }
            }
            //设置申请单的状态为驳回状态，设置驳回原因
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(saveParam.getRejectReason());
            //更新数据
            applicationMapper.update(application);
        }
    }

    //处理当前申请单的审批人相关信息
    private void auditUserList(AuditVO auditVO) {
        //准备存储审批人姓名和id的集合
        List<String> auditUsernameList =  new ArrayList<>();
        List<Long> auditUserIdList =  new ArrayList<>();
        //查询当前登录用户审批的申请单下所有的审批人
        List<AuditVO> auditVOS = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //判断auditVOS是否为空
        if(auditVOS==null)
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        for (int i = 0; i < auditVOS.size(); i++) {
            Long userId = auditVOS.get(i).getAuditUserId();
            //将userId赋值到auditUserIdList集合中
            auditUserIdList.add(userId);
            UserVO userVO = userMapper.selectByParentId(userId);
            //将审批人姓名存储到auditUsernameList集合中
            auditUsernameList.add(userVO.getUsername());
        }
        //存储审批人的姓名时，使用逗号隔开
        //准备一个工具，进行值与值之间的拼接   stringJoiner.add("zhangsan") stringJoiner.add("lisi")   zhangsan,lisi
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList) {
            stringJoiner.add(username);
        }
        //将拼接好的审批人姓名赋值到applicationVO中
        auditVO.setAuditUsernameList(stringJoiner.toString());
        auditVO.setAuditUserIdList(auditUserIdList);
    }
}
